package com.baoteng.rbspy.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mustache.MustacheResourceTemplateLoader;
import org.springframework.stereotype.Service;

import com.baoteng.rbspy.config.car.ConstantConfig;
import com.baoteng.rbspy.config.car.URLConfig;
import com.baoteng.rbspy.model.Model;
import com.baoteng.rbspy.model.renewal.RenewalCheckPO;
import com.baoteng.rbspy.model.renewal.RenewalPO;
import com.baoteng.rbspy.model.request.RenewalDetailsRequest;
import com.baoteng.rbspy.model.request.RenewalRequest;
import com.baoteng.rbspy.model.response.ResponseModel;
import com.baoteng.rbspy.service.KindService;
import com.baoteng.rbspy.service.OkHttpClientService;
import com.baoteng.rbspy.service.PrivyService;
import com.baoteng.rbspy.service.RenewalService;
import com.baoteng.rbspy.service.VehicleService;
import com.baoteng.rbspy.util.BaseUtil;
import com.baoteng.rbspy.util.DateUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Preconditions;
import com.samskivert.mustache.Mustache;

@Service
public class RenewalServiceImpl implements RenewalService{
	private final Logger LOGGER = LoggerFactory.getLogger(RenewalServiceImpl.class);

	@Autowired
	OkHttpClientService okHttpClientService;

	@Autowired
	private Mustache.Compiler compiler;

	@Autowired
	MustacheResourceTemplateLoader mustacheTemplateLoader;

	@Autowired
	URLConfig urlConfig;

	@Autowired
	VehicleService  vehicleService;
	
	@Autowired
	PrivyService  privyService;
	
	@Autowired
	KindService KindService;
	
	@Autowired
	ConstantConfig constant;
	
	//DAA 商业险 DZA交强
	Comparator<RenewalPO> comparator = (d1, d2) -> {
		long d1Time = d1.getEndDate()!=null?d1.getEndDate().getTime():0;
		long d2Time = d2.getEndDate()!=null?d2.getEndDate().getTime():0;
		long result =d1Time-d2Time;
		if(result==0) {
			if("DAA".equals(d1.getRiskCode())) {
				return -1;
			}else if("DAA".equals(d2.getRiskCode())) {
				return 1;
			}
			return 0;
		}
		return result<0?1:-1;
	};

	public Model<RenewalPO> listRenewal(RenewalRequest request) {
		Preconditions.checkNotNull(request);
		try {
			String strBody = compiler.compile(mustacheTemplateLoader.getTemplate("renewal")).execute(request);
			ResponseModel<Model<RenewalPO>> renewalResponse = okHttpClientService.postJson(urlConfig.getRenewalUrl(),
					strBody, new TypeReference<Model<RenewalPO>>() {});
			return renewalResponse.isSuccessful() && renewalResponse.getBody() != null ? renewalResponse.getBody() : null;
		} catch (Exception e) {
			LOGGER.error("RenewalService listRenwal fail.", e);
		}
		return null;
	}

	public RenewalPO getRenewalInfo(RenewalRequest request) {
		Preconditions.checkNotNull(request);
		Model<RenewalPO> pos = listRenewal(request);
		if (pos != null && pos.getData() != null && !pos.getData().isEmpty()) {
			pos.getData().sort(comparator);
			RenewalPO bi = pos.getData().get(0);
			bi.setCheckPO(checkRenewal(bi.getPolicyNo()));
			RenewalDetailsRequest renewalDetailsRequest = new RenewalDetailsRequest();
			renewalDetailsRequest.setEditType("RENEWAL");
			renewalDetailsRequest.setBizType("PROPOSAL");
			renewalDetailsRequest.setBizNo(bi.getPolicyNo());
			renewalDetailsRequest.setRiskCode(bi.getRiskCode());
			Date defaultDate = BaseUtil.getDefaultInsureStartDate();
			Date startDate = bi.getEndDate()!=null?bi.getEndDate().getTime()>defaultDate.getTime()?new Date(bi.getEndDate().getTime()):defaultDate:defaultDate;
			
			renewalDetailsRequest.setStartDate(DateUtils.dateToString(startDate,"yyyy-MM-dd"));
			renewalDetailsRequest.setStartHour("0");
			renewalDetailsRequest.setEndDate(DateUtils.dateToString(BaseUtil.getInsureEndDate(startDate),"yyyy-MM-dd"));
			renewalDetailsRequest.setEndHour("24");
			renewalDetailsRequest.setOperateDate(DateUtils.dateToString(DateUtils.getToday(),"yyyy-MM-dd"));
			bi.setVehiclePO(vehicleService.renewalVehicleInfo(renewalDetailsRequest));
			bi.setPrivyPO(privyService.renewalPrivyInfo(renewalDetailsRequest));
			bi.setBi(KindService.renewalBIInfo(renewalDetailsRequest));
			if(constant.getBiCode().equals(bi.getRiskCode()) ){
				bi.setBiEndDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(bi.getEndDate().getTime()), ZoneId.of(ZoneId.SHORT_IDS.get("CTT"))));
				bi.setBiNo(bi.getPolicyNo());
			}else {
				bi.setCiEndDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(bi.getEndDate().getTime()), ZoneId.of(ZoneId.SHORT_IDS.get("CTT"))));
				bi.setCiNo(bi.getPolicyNo());
			}
			if(pos.getData().size()>1) {
				RenewalPO ci = pos.getData().get(1);
				if(bi.getEndDate()!=null && ci.getEndDate()!=null) {
					if(bi.getEndDate().getYear()==ci.getEndDate().getYear()) {
						if(constant.getBiCode().equals(ci.getRiskCode()) ){
							bi.setBiEndDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(ci.getEndDate().getTime()), ZoneId.of(ZoneId.SHORT_IDS.get("CTT"))));
							bi.setBiNo(ci.getPolicyNo());
						}else {
							bi.setCiEndDate(LocalDateTime.ofInstant(Instant.ofEpochMilli(ci.getEndDate().getTime()), ZoneId.of(ZoneId.SHORT_IDS.get("CTT"))));
							bi.setCiNo(ci.getPolicyNo());
						}
					}
				}
			}
			checkStartDate(bi);
			return bi;
		}
		return null;
	}
	
	public void checkStartDate(RenewalPO renewalPO) {
		try {
			if(StringUtils.isNotBlank(renewalPO.getBiNo())) {
				ResponseModel<String> checkResponse = okHttpClientService.getHtml(urlConfig.getPrefix()+"prpall/business/browseRenewalPolicy.do?bizNo="+renewalPO.getBiNo(), String.class);
				if(checkResponse.isSuccessful() && StringUtils.isNotBlank(checkResponse.getBody())) {
					Document doc = Jsoup.parse(checkResponse.getBody());
					Elements elements = doc.select("input[id=prpCmain.endDate]");
					String biEndDate = elements!=null? elements.get(0).val():null;
					elements = doc.select("input[id=prpCmain.endHour]");
					String biEndHour = elements!=null? elements.get(0).val():null;
//				Elements elements = doc.select("input[id=prpCmain.startDate]");
//				String biStartDate = elements!=null? elements.get(0).val():null;
//				elements = doc.select("input[id=prpCmain.startHour]");
//				String biStartHour = elements!=null? elements.get(0).val():null;
					if(StringUtils.isNotBlank(biEndDate) && StringUtils.isNotBlank(biEndHour)) {
						if(Integer.valueOf(biEndHour)==24) {
							renewalPO.setBiEndDate(renewalPO.getBiEndDate().plusDays(1));
						}
					}
				}
			}
			if(StringUtils.isNotBlank(renewalPO.getCiNo())) {
				ResponseModel<String> checkResponse = okHttpClientService.getHtml(urlConfig.getPrefix()+"prpall/business/browseRenewalPolicy.do?bizNo="+renewalPO.getCiNo(), String.class);
				if(checkResponse.isSuccessful() && StringUtils.isNotBlank(checkResponse.getBody())) {
					Document doc = Jsoup.parse(checkResponse.getBody());
					Elements elements = doc.select("input[id=prpCmainCI.endDate]");
					String ciEndDate = elements!=null? elements.get(0).val():null;
					elements = doc.select("input[id=prpCmainCI.endHour]");
					String ciEndHour = elements!=null? elements.get(0).val():null;
//				Elements elements = doc.select("input[id=prpCmainCI.startDate]");
//				String ciStartDate = elements!=null? elements.get(0).val():null;
//				elements = doc.select("input[id=prpCmainCI.startHour]");
//				String ciStartHour = elements!=null? elements.get(0).val():null;
					if(StringUtils.isNotBlank(ciEndDate) && StringUtils.isNotBlank(ciEndHour)) {
						if(Integer.valueOf(ciEndHour)==24) {
							renewalPO.setCiEndDate(renewalPO.getCiEndDate().plusDays(1));
						}
					}
				}
			}
		} catch (NumberFormatException e) {
			LOGGER.error("RenewalServiceImpl checkStartDate error.",e);
		}
		
	}
	
	public RenewalCheckPO checkRenewal(String bizNo) {
		ResponseModel<Model<RenewalCheckPO>> checkResponse = okHttpClientService.getJson(urlConfig.getRenewalChkUrl()+ "?bizNo="+bizNo, new TypeReference<Model<RenewalCheckPO>>() {});
		return checkResponse.isSuccessful() && checkResponse.getBody()!=null && checkResponse.getBody().getData()!=null && !checkResponse.getBody().getData().isEmpty()?checkResponse.getBody().getData().get(0):null;
	}
	
	/**
	 * 是否转续保
	 * 0--无法判断
	 * 1--转保
	 * 2--续保
	 * 3--新保
	 * @param request
	 * @return
	 */
	public RenewalPO isRenewal(RenewalRequest request) {
		Preconditions.checkNotNull(request);
		Model<RenewalPO> pos = listRenewal(request);
		RenewalPO po = new RenewalPO();
		po.setRenewalFlag("0");
		if (pos != null && pos.getData() != null && !pos.getData().isEmpty()) {
			pos.getData().sort(comparator);
			for(int i=0;i<2 && i<pos.getData().size();i++) {
				RenewalPO lately = pos.getData().get(i);
				RenewalCheckPO checkPO = checkRenewal(lately.getPolicyNo());
				if(checkPO!=null && "2".equals(checkPO.getRenewalFlag())) {
					if(constant.getBiCode().equals(lately.getRiskCode())) {
						po.setBiNo(lately.getPolicyNo());
					}else {
						po.setCiNo(lately.getPolicyNo());
					}
					po.setRenewalFlag("2");
					if(po.getVehiclePO()==null) {
						RenewalDetailsRequest renewalDetailsRequest = new RenewalDetailsRequest();
						renewalDetailsRequest.setEditType("RENEWAL");
						renewalDetailsRequest.setBizType("PROPOSAL");
						renewalDetailsRequest.setBizNo(lately.getPolicyNo());
						renewalDetailsRequest.setRiskCode(lately.getRiskCode());
						Date defaultDate = BaseUtil.getDefaultInsureStartDate();
						Date startDate = lately.getEndDate()!=null?lately.getEndDate().getTime()>defaultDate.getTime()?new Date(lately.getEndDate().getTime()):defaultDate:defaultDate;
						
						renewalDetailsRequest.setStartDate(DateUtils.dateToString(startDate,"yyyy-MM-dd"));
						renewalDetailsRequest.setStartHour("0");
						renewalDetailsRequest.setEndDate(DateUtils.dateToString(BaseUtil.getInsureEndDate(startDate),"yyyy-MM-dd"));
						renewalDetailsRequest.setEndHour("24");
						renewalDetailsRequest.setOperateDate(DateUtils.dateToString(DateUtils.getToday(),"yyyy-MM-dd"));
						po.setVehiclePO(vehicleService.renewalVehicleInfo(renewalDetailsRequest));
					}
				}
			}
		}
		return po;
	}

}
